package cn.funnymap.lgis.tools.service.metadata.factory;

import cn.funnymap.lgis.tools.service.metadata.model.IServiceMetadata;
import cn.funnymap.lgis.tools.util.UrlCoderUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author jiao xn
 */
public class ServiceMetadataFactory {
    private static final Map<String, IServiceMetadata> SERVICE_REGISTERS = new HashMap<>();

    private ServiceMetadataFactory() {
    }

    public static void register(String serviceServerType, IServiceMetadata serviceMetadata) {
        if (StringUtils.isNotBlank(serviceServerType)) {
            SERVICE_REGISTERS.put(serviceServerType, serviceMetadata);
        }
    }

    public static IServiceMetadata create(String url) {
        // url 解码
        try {
            url = UrlCoderUtil.decode(url);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("服务地址解码失败，" + e.getMessage());
        }


        if (url.contains("?")) {
            url = url.substring(0, url.indexOf("?"));
        }

        // 判断URL是否以特定的Server结尾
        String serviceUrlValidationRegRule = ".*(MapServer|FeatureServer|ImageServer|SceneServer)(/\\d)?$";
        Pattern pattern = Pattern.compile(serviceUrlValidationRegRule);
        Matcher matcher = pattern.matcher(url);

        // 构建GeoSceneService实现类
        if (matcher.find()) {
            String serviceServer = matcher.group(1);
            IServiceMetadata serviceMetadata = SERVICE_REGISTERS.get(serviceServer);
            serviceMetadata.initializeUrl(url);
            return serviceMetadata;
        }

        return null;
    }
}
